﻿using CSReport;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Data;
using System.Collections;
using System.ComponentModel;
using System.IO;

namespace GBBQ
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        protected string mStockID;

        protected int mSHZ;

        protected string mName;

        protected string mSymbol;

        protected static string[] mPathLib = new string[]
		{
			"C:\\Program Files\\new_qlzq_v6\\",
			"D:\\Program Files\\new_qlzq_v6\\",
			"E:\\Program Files\\new_qlzq_v6\\",
			"F:\\Program Files\\new_qlzq_v6\\",
			"G:\\Program Files\\new_qlzq_v6\\",
			"H:\\Program Files\\new_qlzq_v6\\",
			"C:\\new_qlzq_v6\\",
			"D:\\new_qlzq_v6\\",
			"E:\\new_qlzq_v6\\",
			"F:\\new_qlzq_v6\\",
			"G:\\new_qlzq_v6\\",
			"H:\\new_qlzq_v6\\"
		};

        protected static string mDataPath = null;

        public static bool mDEBUG = true;

        protected ArrayList parseData;

        protected ArrayList transData;

        public DataRow mDR_Name;

        public DataRow mDR_DBF;

        public DataRow[] mDR_GBBQ;

        public static bool mExportToExcel = false;

        public bool mParseBZ;

        public bool mParseLY;

        protected SortedDictionary<DateTime, int> mDateIDX;

        public static SortedSet<string> mSuggestStock;

        public static SortedSet<string> mSuggestName;

        public static ulong sUP;

        public static ulong sDOWN;

        public static ulong sSTAB;

        public static ulong sYIN;

        public static ulong sYANG;

        public static ulong sCROSS;

        public static DataSet DS_DBF_TDX = null;

        public static Type[] mDBF_Type_TDX = new Type[]
		{
			typeof(int),
			typeof(string),
			typeof(int),
			typeof(decimal),
			typeof(int),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(int),
			typeof(int),
			typeof(int),
			typeof(int),
			typeof(int),
			typeof(decimal)
		};

        protected static DateTime mHistoryDate;

        protected static bool mHistoryDateSW = false;

        public DataTable mMintues1;

        public static DateTime mFDT1;

        public static bool mFDT1SW = false;

        public static DataTable DT_GBBQ;

        public static string[] GBBQ_Header = new string[]
		{
			"SHZ",
			"Stock",
			"DateNum",
			"Date",
			"Type",
			"Dividend",
			"Price",
			"Transfer",
			"Qty",
			"PreFlow",
			"PreTotal",
			"Flow",
			"Total"
		};

        public static Type[] GBBQ_Type = new Type[]
		{
			typeof(int),
			typeof(string),
			typeof(int),
			typeof(DateTime),
			typeof(int),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal)
		};

        public static string[] mData_Header_TDX = new string[]
		{
			"Date",
			"Open",
			"High",
			"Low",
			"Close",
			"Amount",
			"Volume",
			"Reserved",
			"DateInt",
			"RightFlag",
			"Dividend",
			"Price",
			"Present_Transfer",
			"Qty",
			"RightCAP",
			"Flow",
			"Total",
			"Ratio:Flow/PreFlowCAP",
			"Ratio:Flow/TotalCAP",
			"PreClose",
			"DeltaPreClose",
			"DeltaPreClosePercent",
			"NextClose",
			"DeltaNextClose",
			"DeltaNextClosePercent",
			"PriceNCF",
			"OpenRR",
			"HighRR",
			"LowRR",
			"CloseRR",
			"AmountRR",
			"VolumeRR",
			"PriceNCFRR",
			"CloseRR_MA6",
			"CloseRR_MA16",
			"CloseRR_MA38",
			"CloseRR_MA62",
			"CloseRR_MA180",
			"CloseRR_MAn",
			"CloseRR_LRMA6",
			"CloseRR_LRMA16",
			"CloseRR_LRMA38",
			"CloseRR_LRMA62",
			"CloseRR_LRMAn",
			"Ratio:CloseRR/NCFRR",
			"NER_M1",
			"NER_M3",
			"NER_M6",
			"NER_Y1",
			"NER_Y2",
			"NER_Y3"
		};

        public static Type[] mData_Type_TDX = new Type[]
		{
			typeof(DateTime),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(int),
			typeof(int),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(int),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal),
			typeof(decimal)
		};

        public static string[] mGBBQ_Type_ITM = new string[]
		{
			"Empty",
			"除权除息",   //
			"送配股上市",
			"非流通股上市",
			"未知股本变动",
			"股本变化",
			"增发新股",
			"股份回购",
			"增发新股上市",
			"转配股上市",
			"可转债上市",
			"11?",
			"非流通股缩股",
			"送认购权证",
			"送认沽权证",
			"15?",
			"16?"
		};

        public static IEnumerable mGBBQ_Query;

        public static string mOutput = "导出数据\\";

        public static string mSavedFile_GBBQ = "通达信GBBQ_TDX.xml";

        public static string mSavedFile_GBBQ_Schema = "通达信GBBQ_Schema_TDX.xml";

        public static string mEncoding = "UTF-8";

        protected SortedDictionary<DateTime, ArrayList> mRightInfo;

        protected SortedDictionary<DateTime, ArrayList> mRightEvent;

        public DataRow mDataRowDBF;

        public decimal[] mRightRatio;

        public decimal mNER_M1 = decimal.MinusOne;

        public decimal mNER_M3 = decimal.MinusOne;

        public decimal mNER_M6 = decimal.MinusOne;

        public decimal mNER_Y1 = decimal.MinusOne;

        public decimal mNER_Y2 = decimal.MinusOne;

        public decimal mNER_Y3 = decimal.MinusOne;

        public DataTable mTAB_NER_M1;

        public DataTable mTAB_NER_M3;

        public DataTable mTAB_NER_M6;

        public DataTable mTAB_NER_Y1;

        public DataTable mTAB_NER_Y2;

        public DataTable mTAB_NER_Y3;

        public DataTable DT_Working;

        public static string mLibPath = "data\\";

        public static int mWorkers = 10;

        public static int mActiveWorkers = 0;

        public static int mProgress = 0;

        public static int mProgressN = 100;

        public static double mProcessorLimit = 100.0;

        public static float mProcessorValue;

        public static decimal mMemoryLimit = 100m;

        public static PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes");

        public static PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");

        public static bool mProgressLock = false;

        public static object hProgress = null;

        public static BackgroundWorker mBW;

        public static long mD0;

        public static ulong mSum;

        public static DataTable DT_CurrentList;

        public static ProgressChangedEventHandler hProgressChanged;

        public static RunWorkerCompletedEventHandler hRunWorkerCompleted;

        public static int mTimeOut;

        public static DataTable mGlobalDataTable;

        public string mBrief = "";

        public string mOutputPath = "Output\\";

        public MainWindow()
        {
            InitializeComponent();
        }

        // GBBQ_Reader.Stock_Analysis
        public static DateTime ConvertNumToDate(int dt)
        {
            int num = dt % 100;
            dt -= num;
            int num2 = dt % 10000 / 100;
            dt -= num2 * 100;
            return new DateTime(dt / 10000, num2, num);
        }


        // GBBQ_Reader.Stock_Analysis
        public static void AddGBBQUnitToTable(DataTable dt, Unit_GBBQ unit)
        {
            DataRow dataRow = dt.NewRow();
            dataRow[0] = unit.SHZ;
            dataRow[1] = unit.Stock;
            dataRow[2] = unit.Date;
            dataRow[3] = ConvertNumToDate(unit.Date);
            dataRow[4] = unit.Type;
            dataRow[5] = unit.Dividend;
            dataRow[6] = unit.Price;
            dataRow[7] = unit.Present_Transfer;
            dataRow[8] = unit.Qty;
            dataRow[9] = unit.PreFlow;
            dataRow[10] = unit.PreTotal;
            dataRow[11] = unit.Flow;
            dataRow[12] = unit.Total;
            dt.Rows.Add(dataRow);
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            string appName = "TdxW";
            int xLimitRecords = 5000;
            bool result = false;
            Process[] processesByName = Process.GetProcessesByName(appName);
            if (processesByName.Length < 1)
            {
                //Stock_Analysis.mLogs.LogError(" Process [" + appName + "] doesn't exist !", MethodBase.GetCurrentMethod().Name);
                return;
            }
            new ProcessMemoryReaderApi();
            uint id = (uint)processesByName[0].Id;
            uint arg_C4_0 = 1040u;
            bool bInheritHandle = false;
            IntPtr intPtr = ProcessMemoryReaderApi.OpenProcess(arg_C4_0, bInheritHandle, id);
            IntPtr lpAddress = (IntPtr)0;
            ProcessMemoryReaderApi.MEMORY_BASIC_INFORMATION mEMORY_BASIC_INFORMATION = default(ProcessMemoryReaderApi.MEMORY_BASIC_INFORMATION);
            uint dwLength = (uint)Marshal.SizeOf(typeof(ProcessMemoryReaderApi.MEMORY_BASIC_INFORMATION));
            int j = 1;
            bool flag = false;
            byte[] array = null;
            int num = 29;
            int num2 = 10;
            int num3 = -1;
            while (j > 0)
            {
                j = ProcessMemoryReaderApi.VirtualQueryEx(intPtr, lpAddress, out mEMORY_BASIC_INFORMATION, dwLength);
                lpAddress = (IntPtr)((long)((ulong)((int)mEMORY_BASIC_INFORMATION.BaseAddress + (int)mEMORY_BASIC_INFORMATION.RegionSize)));
                if (mEMORY_BASIC_INFORMATION.RegionSize >= 512000u)
                {
                    flag = (mEMORY_BASIC_INFORMATION.Type == ProcessMemoryReaderApi.TypeEnum.MEM_PRIVATE && mEMORY_BASIC_INFORMATION.Protect == ProcessMemoryReaderApi.AllocationProtectEnum.PAGE_READWRITE && mEMORY_BASIC_INFORMATION.State == ProcessMemoryReaderApi.StateEnum.MEM_COMMIT);
                    if (flag)
                    {
                        array = new byte[mEMORY_BASIC_INFORMATION.RegionSize + 1u];
                        IntPtr value;
                        flag = ProcessMemoryReaderApi.ReadProcessMemory(intPtr, mEMORY_BASIC_INFORMATION.BaseAddress, array, mEMORY_BASIC_INFORMATION.RegionSize, out value);
                        if (flag)
                        {
                            string text = "";
                            int num4 = 0;
                            while ((long)num4 < Math.Min((long)((ulong)((int)value)), (long)(num * num2)))
                            {
                                string arg_1C4_0 = text;
                                char c = (char)array[num4];
                                text = arg_1C4_0 + c.ToString();
                                num4++;
                            }
                            num3 = text.IndexOf("000001");
                            flag = (num3 >= 0);
                            for (int k = 1; k < 5; k++)
                            {
                                flag &= (text.IndexOf("000001", num3 + num * k) >= 0);
                            }
                            if (flag)
                            {
                                break;
                            }
                        }
                    }
                }
            }
            ProcessMemoryReaderApi.CloseHandle(intPtr);
            num3--;
            if (flag)
            {
                int num5 = (int)Math.Floor((double)((ulong)mEMORY_BASIC_INFORMATION.RegionSize - (ulong)((long)num3)) / num);
                DT_GBBQ = new DataTable();
                DT_GBBQ.TableName = "GBBQ_TDX";
                for (int i = 0; i < 13; i++)
                {
                    DT_GBBQ.Columns.Add(GBBQ_Header[i]);
                    DT_GBBQ.Columns[i].DataType = GBBQ_Type[i];
                }

                char[] array2 = new char[6];
                //new byte[4];
                if (xLimitRecords > 0 && xLimitRecords < num5)
                {
                    //num5 = xLimitRecords;
                }
                int l = 0;
                while (l < num5)
                {
                    Unit_GBBQ unit_GBBQ = default(Unit_GBBQ);
                    int num6 = num3 + l * num;
                    unit_GBBQ.SHZ = array[num6];
                    array2[0] = (char)array[num6 + 1];
                    array2[1] = (char)array[num6 + 2];
                    array2[2] = (char)array[num6 + 3];
                    array2[3] = (char)array[num6 + 4];
                    array2[4] = (char)array[num6 + 5];
                    array2[5] = (char)array[num6 + 6];
                    unit_GBBQ.Stock = new string(array2);
                    unit_GBBQ.Date = BitConverter.ToInt32(array, num6 + 8);
                    unit_GBBQ.Type = (int)(array[num6 + 12] - 0);
                    Type_GBBQ type_GBBQ = (Type_GBBQ)unit_GBBQ.Type;
                    if (type_GBBQ == Type_GBBQ.DIVIDEND || type_GBBQ == Type_GBBQ.ISSUENEW)
                    {
                        goto IL_360;
                    }
                    switch (type_GBBQ)
                    {
                        case Type_GBBQ.DRAWINGBACK:
                        case Type_GBBQ.CALLWARRANT:
                        case Type_GBBQ.PUTWARRANT:
                            goto IL_360;
                        default:
                            unit_GBBQ.PreFlow = BitConverter.ToSingle(array, num6 + 13);
                            unit_GBBQ.PreTotal = BitConverter.ToSingle(array, num6 + 17);
                            unit_GBBQ.Flow = BitConverter.ToSingle(array, num6 + 21);
                            unit_GBBQ.Total = BitConverter.ToSingle(array, num6 + 25);
                            break;
                    }
                IL_3FA:
                    if (unit_GBBQ.Date >= 1)
                    {
                        AddGBBQUnitToTable(DT_GBBQ, unit_GBBQ);
                        result = true;
                        l++;
                        continue;
                    }
                    break;
                IL_360:
                    unit_GBBQ.Dividend = BitConverter.ToSingle(array, num6 + 13);
                    unit_GBBQ.Price = BitConverter.ToSingle(array, num6 + 17);
                    unit_GBBQ.Present_Transfer = BitConverter.ToSingle(array, num6 + 21);
                    unit_GBBQ.Qty = BitConverter.ToSingle(array, num6 + 25);
                    goto IL_3FA;
                }
                try
                {
                    if (!Directory.Exists(mOutput))
                    {
                        Directory.CreateDirectory(System.IO.Path.Combine(Directory.GetCurrentDirectory(), mOutput));
                    }
                    //DT_GBBQ.WriteXml(System.IO.Path.Combine(Directory.GetCurrentDirectory(), mOutput, mSavedFile_GBBQ), XmlWriteMode.WriteSchema);
                    CSExports.ExportToText(System.IO.Path.Combine(Directory.GetCurrentDirectory(), mOutput, mSavedFile_GBBQ.Replace(".xml", "") + ".txt"), DT_GBBQ, "\t", null);
                    //CSExports.ExportToExcel(new DataSet
                    //{
                    //    Tables = 
				    //{
					//    DT_GBBQ
				    //}
                    //}, null, System.IO.Path.Combine(Directory.GetCurrentDirectory(), mOutput, mSavedFile_GBBQ.Replace(".xml", "") + ".xls"));
                }
                catch (IOException)
                {
                }
                return;
            }
            return;
        }
        
    }
}
